package team.pwy.controller;

import cn.hutool.crypto.digest.DigestUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import team.pwy.consts.RbmConsts;
import team.pwy.mapper.CouponMapper;
import team.pwy.pojo.entity.Coupon;
import team.pwy.pojo.entity.User;
import team.pwy.service.UserService;
import team.pwy.util.JWTUtils;
import team.pwy.vo.Result;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("login/{account}/{password}")
    public Result login(@PathVariable("account") String account, @PathVariable("password") String password) {

        User user = userService.findByAccount(account);

        if (!bCryptPasswordEncoder.matches(password, user.getPassword())) {
            return new Result("500", "密码错误");
        }
        String token = JWTUtils.geneJsonWebToken(user);
        return new Result("200", "登录成功", token);
    }

    @GetMapping("{account}")
    public Result findByAccount(@PathVariable("account") String account) {
        return userService.findByAccount(account) != null ? new Result("404", "用户名重复") : new Result("200", "用户名不重复");
    }

    @PostMapping("/register")
    public Result register(User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        Integer register = userService.register(user);

        return register == 1 ? new Result("200", "注册成功") : new Result("404", "注册失败");

    }

    @GetMapping
    public Result getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = JWTUtils.checkJWT(token);
        Integer id = claims.get("id", Integer.class);
        User user = userService.findByUserId(id);
        return user != null ? new Result("200", "用户信息", user) : new Result("400", "未登录");
    }


    @GetMapping("/phone/{phone}")
    public Result getPhone(@PathVariable("phone") String phone) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            String a = String.valueOf(random.nextInt(10));
            code.append(a);
        }
        ValueOperations vop = redisTemplate.opsForValue();
        vop.set("phoneTV",phone);
        vop.set("code",code,1, TimeUnit.MINUTES);
        return new Result("200", "验证码发送成功");
    }

    @PostMapping("/updataUser")
    public Result updateMessage(User user) {
        Integer updateMessage = userService.updateMessage(user);
        return updateMessage == 1 ? new Result("200", "修改成功") : new Result("404", "修改失败");

    }

    @GetMapping("phoneLogin")
    public Result getPAC(String phone, String cod) {
        ValueOperations vop = redisTemplate.opsForValue();
        ListOperations lop = redisTemplate.opsForList();
        User user = userService.findByPhone(phone);
        String code = (String) vop.get("code");
        if (code==null){
            return new Result("400","验证码已过期 请重新获取");
        }else if (!cod.equals(code)&& !cod.isEmpty()) {
            return new Result("500", "验证码错误");
        } else if (cod.isEmpty()) {
            return new Result("505", "请输入验证码");
        }else if (user == null) {
            String account = userService.account();
            String password = DigestUtil.md5Hex(userService.password());
            userService.addUser(account, password, phone);
            User user1 = userService.findByPhone(phone);
            List phoneList = lop.range("phone", 0, -1);
            if (!phoneList.contains(phone)) {
                lop.leftPush("phone",phone);
                rabbitTemplate.convertAndSend(RbmConsts.PHO_QUEUE,phone);
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.MONTH, 1);
                Integer uid = user1.getId();
                Coupon coupon = new Coupon(null, 10, uid, "新人专享", date, cal.getTime(), null, 0);
                couponMapper.add(coupon);
                String token = JWTUtils.geneJsonWebToken(user1);
                return new Result("200", "登陆成功", token);
            }
            String token = JWTUtils.geneJsonWebToken(user1);
            return new Result("200", "登陆成功", token);
        }
        String token = JWTUtils.geneJsonWebToken(user);
        return new Result("200", "登陆成功", token);
    }
}
